package com.ttnet.authentication;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import com.ttnet.bo.UserBo;
import com.ttnet.model.User;

@Component(value = "customSpringAuthentication")
public class CustomSpringAuthentication implements AuthenticationProvider {
	@Inject
	private UserBo userBo;

	private AuthUser authUser;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		boolean isAuthenticated = false;
		String password = (String) authentication.getCredentials();
		String userName = (String) authentication.getPrincipal();

		User user = userBo.getUserByUserName(userName);

		if (user != null) {

			try {
				if (user.getPassword().equals(password)) {
					isAuthenticated = true;
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}

			if (isAuthenticated) {

				authUser = new AuthUser();

				authUser.setAuthenticated(true);

				List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
				authorities.add(new SimpleGrantedAuthority(user.getRole().getName()));
				authUser.setAuthorities(authorities);

				authUser.setCredentials(authentication.getCredentials());
				authUser.setName(userName);
				authUser.setAuthorityName(user.getRole().getName());

				WebAuthenticationDetails wad = (WebAuthenticationDetails) authentication.getDetails();
				String ip = wad.getRemoteAddress();
				authUser.setIp(ip);

				return authUser;
			} else {

				throw new AuthenticationException("Kullan\u0131c\u0131/\u015Eifre Hatas\u0131") {
				};
			}

		} else {
			throw new AuthenticationException("Kullan\u0131c\u0131/\u015Eifre Hatas\u0131") {
			};
		}
	}

	public AuthUser getAuthUser() {
		return authUser;
	}

	@Override
	public boolean supports(Class<? extends Object> authentication) {
		return true;
	}
}
